/*
 * Copyright (c) 2022-2022 Huawei Technologies Co., Ltd. All rights reserved.
 * Copyright (c) 2022-2022 Huawei Device Co., Ltd. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 *    conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 *    of conditions and the following disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 *    to endorse or promote products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#ifdef LOSCFG_IPC_CONTAINER
#include "los_ipc_container.h"
#include "los_config.h"
#include "los_queue_debug_pri.h"
#include "los_sem_debug_pri.h"
#include "los_process_pri.h"
#include "vnode.h"
#include "proc_fs.h"

#define SHM_SEG_FREE    0x2000
#define SHM_MAX_PAGES 4096
#define SHM_MAX (SHM_MAX_PAGES * PAGE_SIZE)
#define SHM_MIN 1
#define SHM_MNI 192
#define SHM_SEG 128
#define SHM_ALL (SHM_MAX_PAGES)

const int IPC_INIT_NUM = 3;
extern struct ContainerConfig g_containerConfig;
UINT32 g_currentIpcContainerNum = 1;

IpcContainer g_rootIpcContainer;

static UINT32 InitOsQueue(IpcContainer *ipcContainer)
{
    LosQueueCB *queueNode = NULL;
    UINT32 index;
    UINT32 size = LOSCFG_BASE_IPC_QUEUE_LIMIT * sizeof(LosQueueCB);

    ipcContainer->allQueue = (LosQueueCB *)LOS_MemAlloc(m_aucSysMem0, size);
    if (ipcContainer->allQueue == NULL) {
        return LOS_ERRNO_QUEUE_NO_MEMORY;
    }
    (VOID)memset_s(ipcContainer->allQueue, size, 0, size);
    LOS_ListInit(&ipcContainer->freeQueueList);

    UINT32 queueFdSetSize = sizeof(fd_set);
    (VOID)memset_s(&ipcContainer->queueFdSet, queueFdSetSize, 0, queueFdSetSize);

    UINT32 queueTableSize = LOSCFG_BASE_IPC_QUEUE_LIMIT * sizeof(struct mqarray);
    (VOID)memset_s(ipcContainer->queueTable, queueTableSize, 0, queueTableSize);

    for (index = 0; index < LOSCFG_BASE_IPC_QUEUE_LIMIT; ++index) {
        queueNode = ((LosQueueCB *)ipcContainer->allQueue) + index;
        queueNode->queueID = index;
        LOS_ListTailInsert(&ipcContainer->freeQueueList, &queueNode->readWriteList[OS_QUEUE_WRITE]);
    }

    for (index = 0; index < MAX_MQ_FD; ++index) {
        ipcContainer->mqPrivBuf[index] = NULL;
    }

    return LOS_OK;
}

static UINT32 InitOsShm(IpcContainer *ipcContainer)
{
    UINT32 ret;
    UINT32 i;
    ipcContainer->shmInfo.shmmax = SHM_MAX;
    ipcContainer->shmInfo.shmmin = SHM_MIN;
    ipcContainer->shmInfo.shmmni = SHM_MNI;
    ipcContainer->shmInfo.shmseg = SHM_SEG;
    ipcContainer->shmInfo.shmall = SHM_ALL;

    ret = LOS_MuxInit(&(ipcContainer->sysvShmMux), NULL);
    if (ret != LOS_OK) {
        return ret;
    }

    ipcContainer->shmSegs = LOS_MemAlloc((VOID *)OS_SYS_MEM_ADDR, sizeof(struct shmIDSource) * ipcContainer->shmInfo.shmmni);
    if (ipcContainer->shmSegs == NULL) {
        (VOID)LOS_MuxDestroy(&(ipcContainer->sysvShmMux));
        return ENOMEM;
    }
    (VOID)memset_s(ipcContainer->shmSegs, (sizeof(struct shmIDSource) * ipcContainer->shmInfo.shmmni),
                   0, (sizeof(struct shmIDSource) * ipcContainer->shmInfo.shmmni));

    for (i = 0; i < ipcContainer->shmInfo.shmmni; i++) {
        ipcContainer->shmSegs[i].status = SHM_SEG_FREE;
        ipcContainer->shmSegs[i].ds.shm_perm.seq = i + 1;
        LOS_ListInit(&(ipcContainer->shmSegs)[i].node);
    }
    ipcContainer->shmUsedPageCount = 0;

    return LOS_OK;

}

static UINT32 InitIpcContainer(IpcContainer *ipcContainer)
{
    UINT32 ret;
    if (InitOsQueue(ipcContainer) != LOS_OK) {
        return LOS_NOK;
    }
    
    ret = pthread_mutex_init(&ipcContainer->mqueueMutex, NULL);
    if (ret != LOS_OK) {
        return LOS_NOK;
    }
    ret = InitOsShm(ipcContainer);
    if (ret != LOS_OK) {
        return ret;
    }

    return LOS_OK;
}

UINT32 InitRootIpcContainer(IpcContainer *ipcContainer)
{
    if (InitIpcContainer(ipcContainer) != LOS_OK) {
        return LOS_NOK;
    }

    atomic_set(&ipcContainer->count, IPC_INIT_NUM);
    ContainerAllocVnum(&(ipcContainer->containerBase.vnum));
    return LOS_OK;
}

static IpcContainer *CreateIpcContainer()
{
    if (g_currentIpcContainerNum > g_containerConfig.MaxIpcContainer) {
        PRINT_ERR("CreateIPCContainer failed, reach to max container config.\n");
        return NULL;
    }

    IpcContainer *ipcContainer = NULL;

    UINT32 size = sizeof(IpcContainer);
    ipcContainer = LOS_MemAlloc(m_aucSysMem1, size);

    if (ipcContainer == NULL) {
        PRINT_ERR("CreateIpcContainer failed to malloc memory.\n");
        return NULL;
    }

    ipcContainer->allQueue = NULL;
    ipcContainer->shmSegs  = NULL;

    UINT32 intSave;
    SCHEDULER_LOCK(intSave);
    g_currentIpcContainerNum += 1;
    SCHEDULER_UNLOCK(intSave);

    return ipcContainer;
}

static IpcContainer *CreateNewIpcContainer(IpcContainer *runIpcContainer)
{
    IpcContainer *newIpcContainer = NULL;
    newIpcContainer = CreateIpcContainer();
    if (newIpcContainer == NULL) {
        PRINT_ERR("newIpcContainer is NULL.\n");
        return NULL;
    }
    UINT32 ret =  InitIpcContainer(newIpcContainer);
    if (ret != LOS_OK) {
        return NULL;
    }

    atomic_set(&newIpcContainer->count, 1);;
    ContainerAllocVnum(&(newIpcContainer->containerBase.vnum));

    return newIpcContainer;
}


IpcContainer *HandleIpcContainer(unsigned long flags, IpcContainer *runIpcContainer)
{
    IpcContainer *newIpcContainer = NULL;

    if (!(flags & CLONE_NEWIPC)) {
        GetIpcContainer(runIpcContainer);
        return runIpcContainer;
    }

    newIpcContainer = CreateNewIpcContainer(runIpcContainer);
    if (newIpcContainer == NULL) {
        PRINT_ERR("newIpcContainer is NULL.\n");
        return NULL;
    }
    return newIpcContainer;
}

void FreeIpcContainer(IpcContainer **ipcContainer)
{
    if (ipcContainer != NULL) {
        if ((*ipcContainer)->allQueue != NULL) {
            LOS_MemFree(m_aucSysMem0, (*ipcContainer)->allQueue);
            (*ipcContainer)->allQueue = NULL;
        }

        if ((*ipcContainer)->shmSegs != NULL) {
              LOS_MemFree((VOID *)OS_SYS_MEM_ADDR, (*ipcContainer)->shmSegs);
        }

        LOS_MemFree(m_aucSysMem1, *ipcContainer);
        *ipcContainer = NULL;
    }

    UINT32 intSave;
    SCHEDULER_LOCK(intSave);
    g_currentIpcContainerNum -= 1;
    SCHEDULER_UNLOCK(intSave);
}

INT32 ReplaceIpcContainerInBundle(ContainerBundle* bundle, struct IpcContainer *targetIpcContainer)
{
    if (bundle->ipcContainer) {
        DerefIpcContainer(&bundle->ipcContainer);
    }

    bundle->ipcContainer = targetIpcContainer;
    GetIpcContainer(targetIpcContainer);

    return LOS_OK;
}

IpcContainer *GetCurrIpcContainer(void)
{
    return OsCurrProcessGet()->containerBundle->ipcContainer;
}

void OsDealBeforeAssign(UINT32 flags)
{
    if (!(flags & CLONE_NEWIPC)) {
        return;
    }
#ifdef LOSCFG_KERNEL_SHM
    OsDealShmNattchSub();
#endif
}
#endif

